/**
 * @file 监控系统看板页面
 * @date 2025/10/28 21:00:00
 * @author lyqjob@yeah.net
 * @description 监控系统数据可视化看板，展示关键性能指标、错误统计、用户行为等数据
 */

import {  useState, useEffect  } from 'react';
import { Card, Row, Col, Statistic, Typography, Select, Tabs } from 'antd';
import { Pie, Line, Column } from '@ant-design/plots';
import styles from './index.less';
import { ReloadOutlined, BarChartOutlined, LineChartOutlined, PieChartOutlined, ExclamationCircleOutlined, EyeOutlined, UserOutlined, ClockCircleOutlined } from '@ant-design/icons';
import { adminApi } from '@/services/admin';


const { Title, Text, Paragraph } = Typography;
// const { RangePicker } = DatePicker;
const { Option } = Select;

// 模拟错误类型分布数据
const errorTypeData = [
  { name: 'JS错误', value: 45 },
  { name: '资源加载', value: 25 },
  { name: '请求错误', value: 20 },
  { name: 'Promise错误', value: 10 },
];

// 模拟性能趋势数据
const performanceTrendData = [
  { time: '00:00', value: 1200, type: '加载时间(ms)' },
  { time: '04:00', value: 1100, type: '加载时间(ms)' },
  { time: '08:00', value: 1500, type: '加载时间(ms)' },
  { time: '12:00', value: 2000, type: '加载时间(ms)' },
  { time: '16:00', value: 1800, type: '加载时间(ms)' },
  { time: '20:00', value: 1600, type: '加载时间(ms)' },
  { time: '00:00', value: 800, type: '首次渲染(ms)' },
  { time: '04:00', value: 750, type: '首次渲染(ms)' },
  { time: '08:00', value: 1000, type: '首次渲染(ms)' },
  { time: '12:00', value: 1300, type: '首次渲染(ms)' },
  { time: '16:00', value: 1200, type: '首次渲染(ms)' },
  { time: '20:00', value: 1100, type: '首次渲染(ms)' },
  { time: '00:00', value: 300, type: '首字节(ms)' },
  { time: '04:00', value: 280, type: '首字节(ms)' },
  { time: '08:00', value: 350, type: '首字节(ms)' },
  { time: '12:00', value: 420, type: '首字节(ms)' },
  { time: '16:00', value: 380, type: '首字节(ms)' },
  { time: '20:00', value: 350, type: '首字节(ms)' },
];

// 模拟用户行为数据
const behaviorData = [
  { name: '页面浏览', count: 1200 },
  { name: '按钮点击', count: 3500 },
  { name: '表单提交', count: 450 },
  { name: 'API请求', count: 2800 },
  { name: '路由切换', count: 800 },
];

const COLORS = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FECA57'];

const MonitorPanel = () => {
  const [dateRange] = useState(null);
  const [activeTab, setActiveTab] = useState('1');

  // 模拟数据加载
  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    // 加载监控数据
    
    // 检查dateRange是否为空，如果为空则使用默认时间范围（最近24小时）
    if (!dateRange || !Array.isArray(dateRange)) {
      // 使用默认时间范围
      const now = Date.now();
      const twentyFourHoursAgo = now - 24 * 60 * 60 * 1000;
      
      const promiseAll = Promise.all([
        adminApi.getStatsBehavior({startTime: twentyFourHoursAgo, endTime: now}),
        adminApi.getStatsError({ startTime: twentyFourHoursAgo, endTime: now }),
        adminApi.getStatsPerformance({ startTime: twentyFourHoursAgo, endTime: now })
      ]);

      promiseAll.then(_results => {
        const [,] = _results[1]; // errorData
        const [,] = _results[0]; // behaviorData  
        const [,] = _results[2]; // performanceData
        // 处理默认时间范围的数据
      }).catch(_error => {
        // 处理错误
      });
      return;
    }
    
    // dateRange有效时的正常处理
    const promiseAll = Promise.all([
      adminApi.getStatsBehavior({startTime: dateRange[0], endTime : dateRange[1]}),
      adminApi.getStatsError({ startTime: dateRange[0], endTime: dateRange[1] }),
      adminApi.getStatsPerformance({ startTime: dateRange[0], endTime: dateRange[1]})
    ]);

    promiseAll.then(_results => {
      // 处理结果数据
    }).catch(_error => {
      // 处理错误
    });

   
  };

  const handleRefresh = () => {
    loadData();
  };

  const renderErrorTypePieChart = () => {
    const config = {
      data: errorTypeData,
      angleField: 'value',
      colorField: 'name',
      radius: 0.8,
      
      label: {
        text: 'value',
        content: ({ percent }) => `${(percent * 100).toFixed(0)}%`,
        style: {
          fontSize: 14,
          textAlign: 'center',
        },
      },
      interactions: [{ type: 'element-selected' }, { type: 'element-active' }],
      color: COLORS,
    };
    return <Pie {...config} />;
  };

  const renderPerformanceTrendChart = () => {
    const config = {
      data: performanceTrendData,
      xField: 'time',
      yField: 'value',
      seriesField: 'type',
      legend: {
        position: 'top',
      },
      smooth: true,
      animation: {
        appear: {
          animation: 'path-in',
          duration: 1000,
        },
      },
      yAxis: {
        label: {
          formatter: (v) => `${v}ms`,
        },
      },
      color: ['#FF6B6B', '#4ECDC4', '#45B7D1'],
    };
    return <Line {...config} />;
  };

  const renderBehaviorBarChart = () => {
    const config = {
      data: behaviorData,
      xField: 'name',
      yField: 'count',
      label: {
        position: 'middle',
        style: {
          fill: '#FFFFFF',
          opacity: 0.6,
        },
      },
      colorField: 'name',
      color: COLORS,
    };
    return <Column {...config} />;
  };

  return (
    <div className={styles.container}>
      {/* 页面标题和筛选器 */}
      <div className={styles.header}>
        <div className={styles.titleContainer}>
          <Title level={4} className={styles.title}>监控看板</Title>
          <Paragraph className={styles.subtitle}>实时监控系统性能、错误和用户行为</Paragraph>
        </div>
        <div className={styles.filterContainer}>
          <Select 
            defaultValue="24h" 
            style={{ width: 120 }} 
            className={styles.filterItem}
          >
            <Option value="1h">最近1小时</Option>
            <Option value="24h">最近24小时</Option>
            <Option value="7d">最近7天</Option>
            <Option value="30d">最近30天</Option>
          </Select>
          {/* <RangePicker 
            onChange={handleDateRangeChange} 
            className={styles.filterItem}
          /> */}
          <ReloadOutlined 
            onClick={handleRefresh} 
            className={styles.refreshIcon}
          />
        </div>
      </div>

      <Spin spinning={false}>
        {/* 关键指标卡片 */}
        <Row gutter={16} className={styles.metricsRow}>
          <Col span={6}>
            <Card className={styles.metricCard}>
              <Statistic
                title="今日错误数"
                value={128}
                precision={0}
                valueStyle={{ color: '#FF6B6B' }}
                prefix={<ExclamationCircleOutlined />}
                suffix="次"
              />
              <Text type="danger" className={styles.metricChange}>↑ 12% 较昨日</Text>
            </Card>
          </Col>
          <Col span={6}>
            <Card className={styles.metricCard}>
              <Statistic
                title="平均加载时间"
                value={1560}
                precision={0}
                valueStyle={{ color: '#4ECDC4' }}
                prefix={<ClockCircleOutlined />}
                suffix="ms"
              />
              <Text type="success" className={styles.metricChange}>↓ 8% 较昨日</Text>
            </Card>
          </Col>
          <Col span={6}>
            <Card className={styles.metricCard}>
              <Statistic
                title="今日访问量"
                value={5842}
                precision={0}
                valueStyle={{ color: '#45B7D1' }}
                prefix={<EyeOutlined />}
                suffix="次"
              />
              <Text type="success" className={styles.metricChange}>↑ 23% 较昨日</Text>
            </Card>
          </Col>
          <Col span={6}>
            <Card className={styles.metricCard}>
              <Statistic
                title="活跃会话数"
                value={142}
                precision={0}
                valueStyle={{ color: '#96CEB4' }}
                prefix={<UserOutlined />}
                suffix="个"
              />
              <Text type="secondary" className={styles.metricChange}>实时更新</Text>
            </Card>
          </Col>
        </Row>

        {/* 图表区域 */}
        <Tabs 
          activeKey={activeTab} 
          onChange={setActiveTab} 
          className={styles.chartTabs}
          items={[
            {
              key: '1',
              label: <span><PieChartOutlined /> 错误分布</span>,
              children: (
                <Row gutter={16}>
                  <Col span={12}>
                    <Card title="错误类型分布" className={styles.chartCard}>
                      {renderErrorTypePieChart()}
                    </Card>
                  </Col>
                  <Col span={12}>
                    <Card title="错误趋势" className={styles.chartCard}>
                      {renderPerformanceTrendChart()}
                    </Card>
                  </Col>
                </Row>
              ),
            },
            {
              key: '2',
              label: <span><LineChartOutlined /> 性能监控</span>,
              children: (
                <Card title="性能指标趋势" className={styles.chartCard}>
                  {renderPerformanceTrendChart()}
                </Card>
              ),
            },
            {
              key: '3',
              label: <span><BarChartOutlined /> 用户行为</span>,
              children: (
                <Card title="用户行为分布" className={styles.chartCard}>
                  {renderBehaviorBarChart()}
                </Card>
              ),
            },
          ]}
        />
      </Spin>
    </div>
  );
};

export default MonitorPanel;